const { Op } = require('sequelize')
const AiConfig = require('../models/AiConfig')
const AiService = require('../services/aiService')
const logger = require('../utils/logger')
const { HTTP_STATUS } = require('../utils/constants')
const { asyncHandler } = require('../middleware/errorHandler')

/**
 * 转换配置对象，将 baseUrl 映射为 apiUrl
 */
const transformConfigForResponse = (config) => {
  if (!config) return config
  
  const configData = config.toJSON ? config.toJSON() : config
  const result = { ...configData }
  
  if (configData.baseUrl) {
    result.apiUrl = configData.baseUrl
    delete result.baseUrl
  }
  
  // 将数据库的独立字段重新组合成前端期望的parameters对象
  result.parameters = {
    temperature: configData.temperature || 0.7,
    maxTokens: configData.maxTokens || 2000,
    topP: configData.topP || 0.9
  }
  
  // 移除独立的参数字段
  delete result.temperature
  delete result.maxTokens
  delete result.topP
  
  return result
}

/**
 * 转换配置列表
 */
const transformConfigsForResponse = (configs) => {
  if (Array.isArray(configs)) {
    return configs.map(transformConfigForResponse)
  }
  if (configs.rows) {
    return {
      ...configs,
      rows: configs.rows.map(transformConfigForResponse)
    }
  }
  return configs
}

class AiConfigController {
  /**
   * 创建AI配置
   */
  static createConfig = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const configData = req.body
    
    // 将前端的 apiUrl 映射到数据库的 baseUrl
    const dbData = {
      ...configData,
      userId
    }
    
    if (configData.apiUrl) {
      dbData.baseUrl = configData.apiUrl
      delete dbData.apiUrl
    }
    
    // 处理 parameters 对象，将其展开到对应的数据库字段
    if (configData.parameters) {
      if (configData.parameters.temperature !== undefined) {
        dbData.temperature = configData.parameters.temperature
      }
      if (configData.parameters.maxTokens !== undefined) {
        dbData.maxTokens = configData.parameters.maxTokens
      }
      if (configData.parameters.topP !== undefined) {
        dbData.topP = configData.parameters.topP
      }
      delete dbData.parameters
    }
    
    const config = await AiConfig.create(dbData)
    
    logger.info('AI config created', {
      userId,
      configId: config.id,
      name: config.name,
      provider: config.provider,
      model: config.model
    })
    
    res.status(HTTP_STATUS.CREATED).json({
      success: true,
      message: 'AI配置创建成功',
      data: {
        config: transformConfigForResponse(config)
      }
    })
  })
  
  /**
   * 获取用户的AI配置列表
   */
  static getUserConfigs = asyncHandler(async (req, res) => {
    const {
      page = 1,
      limit = 20,
      provider,
      isActive,
      search,
      sortBy = 'createdAt',
      sortOrder = 'desc'
    } = req.query
    
    const where = {}
    if (provider) where.provider = provider
    if (isActive !== undefined) where.isActive = isActive === 'true'
    if (search) {
      where[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ]
    }
    
    const configs = await AiConfig.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit),
      order: [[sortBy, sortOrder.toUpperCase()]]
    })
    
    res.json({
      success: true,
      data: transformConfigsForResponse(configs)
    })
  })
  
  /**
   * 获取AI配置详情
   */
  static getConfig = asyncHandler(async (req, res) => {
    const { id } = req.params
    const userId = req.user.id
    
    const config = await AiConfig.findByPk(id)
    
    if (!config) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({
        success: false,
        message: 'AI配置不存在'
      })
    }
    
    // 检查访问权限
    if (config.userId !== userId && !config.isDefault) {
      return res.status(HTTP_STATUS.FORBIDDEN).json({
        success: false,
        message: '无权访问此配置'
      })
    }
    
    res.json({
      success: true,
      data: {
        config: transformConfigForResponse(config)
      }
    })
  })
  
  /**
   * 更新AI配置
   */
  static updateConfig = asyncHandler(async (req, res) => {
    const { configId } = req.params
    const updateData = req.body
    
    const config = await AiConfig.findByPk(configId)
    
    if (!config) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({
        success: false,
        message: 'AI配置不存在'
      })
    }
    
    // 将前端的 apiUrl 映射到数据库的 baseUrl
    const dbUpdateData = { ...updateData }
    if (updateData.apiUrl) {
      dbUpdateData.baseUrl = updateData.apiUrl
      delete dbUpdateData.apiUrl
    }
    
    // 处理 parameters 对象，将其展开到对应的数据库字段
    if (updateData.parameters) {
      if (updateData.parameters.temperature !== undefined) {
        dbUpdateData.temperature = updateData.parameters.temperature
      }
      if (updateData.parameters.maxTokens !== undefined) {
        dbUpdateData.maxTokens = updateData.parameters.maxTokens
      }
      if (updateData.parameters.topP !== undefined) {
        dbUpdateData.topP = updateData.parameters.topP
      }
      delete dbUpdateData.parameters
    }
    
    await AiConfig.update(dbUpdateData, { where: { id: configId } })
    const updatedConfig = await AiConfig.findByPk(configId)
    
    logger.info('AI config updated', {
      configId,
      updatedFields: Object.keys(updateData)
    })
    
    res.json({
      success: true,
      message: 'AI配置更新成功',
      data: {
        config: transformConfigForResponse(updatedConfig)
      }
    })
  })
  
  /**
   * 删除AI配置
   */
  static deleteConfig = asyncHandler(async (req, res) => {
    const { id } = req.params
    const userId = req.user.id
    
    const config = await AiConfig.findByPk(id)
    
    if (!config) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({
        success: false,
        message: 'AI配置不存在'
      })
    }
    
    // 检查所有权
    if (config.userId !== userId) {
      return res.status(HTTP_STATUS.FORBIDDEN).json({
        success: false,
        message: '无权删除此配置'
      })
    }
    
    await AiConfig.destroy({ where: { id, userId } })
    
    logger.info('AI config deleted', {
      userId,
      configId: id,
      name: config.name
    })
    
    res.json({
      success: true,
      message: 'AI配置删除成功'
    })
  })
  
  /**
   * 设置默认配置
   */
  static setDefaultConfig = asyncHandler(async (req, res) => {
    const { configId } = req.params
    
    const config = await AiConfig.findByPk(configId)
    
    if (!config) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({
        success: false,
        message: 'AI配置不存在'
      })
    }
    
    // 先将所有配置设为非默认
    await AiConfig.update({ isDefault: false }, { where: {} })
    // 然后设置当前配置为默认
    await AiConfig.update({ isDefault: true }, { where: { id: configId } })
    
    logger.info('Default AI config set', {
      configId,
      name: config.name
    })
    
    res.json({
      success: true,
      message: '默认配置设置成功'
    })
  })
  
  /**
   * 获取默认配置
   */
  static getDefaultConfig = asyncHandler(async (req, res) => {
    // 查找全局默认配置（isDefault: true）
    const config = await AiConfig.findOne({ where: { isDefault: true, isActive: true } })
    
    if (config) {
      return res.json({
        success: true,
        data: {
          config: transformConfigForResponse(config)
        }
      })
    }
    
    // 如果没有找到默认配置，返回系统默认配置
    const defaultConfig = {
      name: '系统默认配置',
      provider: 'siliconflow',
      model: 'deepseek-ai/DeepSeek-V2.5',
      apiUrl: 'https://api.siliconflow.cn/v1',
      apiKey: '', // 未认证用户需要自己配置
      description: '系统提供的默认AI配置',
      parameters: {
        temperature: 0.7,
        maxTokens: 2000,
        topP: 0.9
      },
      isDefault: true,
      isActive: true
    }
    
    res.json({
      success: true,
      data: {
        config: defaultConfig
      }
    })
  })
  
  /**
   * 测试AI配置连接
   */
  static testConfig = asyncHandler(async (req, res) => {
    const { id } = req.params
    const userId = req.user.id
    
    const config = await AiConfig.findByPk(id)
    
    if (!config) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({
        success: false,
        message: 'AI配置不存在'
      })
    }
    
    // 检查访问权限
    if (config.userId !== userId && !config.isDefault) {
      return res.status(HTTP_STATUS.FORBIDDEN).json({
        success: false,
        message: '无权测试此配置'
      })
    }
    
    const testResult = await AiService.testConnection(config)
    
    logger.info('AI config tested', {
      userId,
      configId: id,
      success: testResult.success,
      responseTime: testResult.responseTime
    })
    
    res.json({
      success: true,
      message: testResult.success ? '连接测试成功' : '连接测试失败',
      data: testResult
    })
  })
  
  /**
   * 切换配置状态
   */
  static toggleConfigStatus = asyncHandler(async (req, res) => {
    const { id } = req.params
    const userId = req.user.id
    
    const config = await AiConfig.findByPk(id)
    
    if (!config) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({
        success: false,
        message: 'AI配置不存在'
      })
    }
    
    // 检查所有权
    if (config.userId !== userId) {
      return res.status(HTTP_STATUS.FORBIDDEN).json({
        success: false,
        message: '无权修改此配置状态'
      })
    }
    
    const updatedConfig = await AiConfig.toggleStatus(id)
    
    logger.info('AI config status toggled', {
      userId,
      configId: id,
      newStatus: updatedConfig.isActive
    })
    
    res.json({
      success: true,
      message: `配置已${updatedConfig.isActive ? '启用' : '禁用'}`,
      data: {
        config: updatedConfig
      }
    })
  })
  
  /**
   * 获取支持的AI模型列表
   */
  static getSupportedModels = asyncHandler(async (req, res) => {
    const { provider } = req.query
    
    let models
    if (provider) {
      models = AiService.getSupportedModels(provider)
    } else {
      const providers = AiService.getSupportedProviders()
      models = {}
      for (const p of providers) {
        models[p] = AiService.getSupportedModels(p)
      }
    }
    
    res.json({
      success: true,
      data: {
        models
      }
    })
  })
  
  /**
   * 获取支持的AI提供商列表
   */
  static getSupportedProviders = asyncHandler(async (req, res) => {
    const providers = AiService.getSupportedProviders()
    
    res.json({
      success: true,
      data: {
        providers
      }
    })
  })
  
  /**
   * 验证配置参数
   */
  static validateParameters = asyncHandler(async (req, res) => {
    const { parameters } = req.body
    
    const errors = AiService.validateParameters(parameters)
    
    res.json({
      success: errors.length === 0,
      message: errors.length === 0 ? '参数验证通过' : '参数验证失败',
      data: {
        valid: errors.length === 0,
        errors
      }
    })
  })
  
  /**
   * 复制配置
   */
  static duplicateConfig = asyncHandler(async (req, res) => {
    const { id } = req.params
    const userId = req.user.id
    const { name } = req.body
    
    const originalConfig = await AiConfig.findByPk(id)
    
    if (!originalConfig) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({
        success: false,
        message: 'AI配置不存在'
      })
    }
    
    // 检查访问权限
    if (originalConfig.userId !== userId && !originalConfig.isDefault) {
      return res.status(HTTP_STATUS.FORBIDDEN).json({
        success: false,
        message: '无权复制此配置'
      })
    }
    
    // 创建副本
    const duplicatedConfig = await AiConfig.create({
      userId,
      name: name || `${originalConfig.name} (副本)`,
      provider: originalConfig.provider,
      model: originalConfig.model,
      apiUrl: originalConfig.apiUrl,
      apiKey: originalConfig.apiKey, // 会重新加密
      parameters: originalConfig.parameters,
      description: originalConfig.description,
      isDefault: false,
      isActive: true
    })
    
    logger.info('AI config duplicated', {
      userId,
      originalConfigId: id,
      newConfigId: duplicatedConfig.id,
      newName: duplicatedConfig.name
    })
    
    res.status(HTTP_STATUS.CREATED).json({
      success: true,
      message: '配置复制成功',
      data: {
        config: duplicatedConfig
      }
    })
  })
}

module.exports = AiConfigController